<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <div class="logo-circle">
          <el-icon :size="32">
            <User />
          </el-icon>
        </div>
        <h2 class="title">系统登录</h2>
      </div>

      <el-radio-group v-model="actionType" class="mode-switch">
        <el-radio label="login">登录</el-radio>
        <el-radio label="register">注册</el-radio>
      </el-radio-group>

      <el-form ref="loginForm" :model="form" :rules="rules" v-if="actionType === 'login'"
        @submit.prevent="handleLoginSubmit">
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :prefix-icon="User" clearable />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" show-password
            clearable />
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary" :loading="loginLoading" class="submit-btn">
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <el-form ref="registerForm" :model="form" :rules="rules" v-if="actionType === 'register'"
        @submit.prevent="handleRegisterSubmit">
        <el-form-item prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :prefix-icon="User" clearable />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" show-password
            clearable />
        </el-form-item>
        <el-form-item prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" :prefix-icon="Message" clearable />
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary" :loading="registerLoading" class="submit-btn">
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { loginAPI, registerAPI } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'
import type { FormInstance } from 'element-plus'

interface LoginResponse {
  data: {
    token: string;
    userId: string;
    username: string;
    nickname: string;
    roles: string; // 注意字段名是 roles
    email: string;
    message?: string;
  };
  status: number;
}

const router = useRouter()
const authStore = useAuthStore()
const actionType = ref('login')
const form = reactive({
  username: 'admin',
  password: '20031026',
  email: ''
})
const loginForm = ref<FormInstance>()
const registerForm = ref<FormInstance>()
const rules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码', 
      trigger: 'blur',
      min: 6,
      max: 20,
    }
  ]
}

const loginLoading = ref(false)
const registerLoading = ref(false)

const handleLoginSubmit = async () => {
  if (!loginForm.value) return;
  try {
    await loginForm.value.validate();
    loginLoading.value = true;
    const response = await loginAPI(form) as unknown as LoginResponse;

    console.log('接口返回数据:', response.data); // 调试输出

    if (response.status === 200) {
      const { token, userId, username, nickname, roles, email } = response.data; // 注意这里是 roles 而不是 role
      // 保存到 Pinia Store
      authStore.login({
        token,
        user: {
          userId,
          username,
          nickname,
          role: roles, // 使用接口返回的 roles 字段
          email,
        },
      });

      console.log('保存后的用户信息:', authStore.userInfo); // 验证数据

      // 跳转到导航页
      const redirectPath = router.currentRoute.value.query.redirect?.toString() || '/navigation';
      await router.replace({
        path: redirectPath,
        query: { timestamp: Date.now() },
      });

      ElNotification.success({
        title: '登录成功',
        message: `欢迎回来，${authStore.userInfo?.nickname}`,
        duration: 2000,
      });
    } else {
      ElMessage.error(response.data?.message || '登录失败');
    }
  } catch (error) {
    ElMessage.error('系统异常，请联系管理员');
  } finally {
    loginLoading.value = false;
  }
};

const handleRegisterSubmit = async () => {
  if (!registerForm.value) return
  try {
    await registerForm.value.validate()
    registerLoading.value = true
    const response = await registerAPI(form)
    if (response.status === 200) {
      ElMessage.success('注册成功，请登录')
      actionType.value = 'login'
    } else {
      ElMessage.error(response.data?.message || '注册失败')
    }
  } catch (error) {
    ElMessage.error('系统异常，请联系管理员')
  } finally {
    registerLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
}

.login-card {
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-circle {
  width: 60px;
  height: 60px;
  margin: 0 auto;
  border: 2px solid #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
}

.title {
  color: #303133;
  margin-top: 20px;
  font-size: 24px;
}

.mode-switch {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.submit-btn {
  width: 100%;
  height: 40px;
}
</style>